<!-- 元数据编辑对话框 -->
<template>
  <CommonDialog v-model="visible" title="导入元数据" :loading="loading" :width="500" @submit="submit" @cancel="cancel">
    <List>
      <ListItem>
        <Checkbox v-model="allSelect" @on-change="selectAllChange">元数据名称 ({{ dataList.length }})</Checkbox>
      </ListItem>

      <ListItem v-for="(item,index) in dataList" :key="index">
        <Checkbox v-model="item.checked">{{item.name}}</Checkbox>
      </ListItem>
    </List>
  </CommonDialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from 'view-ui-plus'

import { metadata } from '@/api/modules/modelSetting'

const emit = defineEmits(['cancel', 'submit'])

// 是否打开弹窗
const visible = ref(true)

// 加载状态
const loading = ref(false)

const allSelect = ref(false)

const dataList = ref([])
const getData = () => {
  loading.value = true
  metadata.tableImp().then(({data})=>{
    const checkedList = data.metadataTable.split(',').filter(item=>item)
    dataList.value = data.tablesList.map(item=>{
      return {
        name: item.name,
        checked: checkedList.includes(item.name)
      }
    })

    if(checkedList.length === data.tablesList.length) {
      allSelect.value = true
    }
  }).finally(()=>{
    loading.value = false
  })
}

const selectAllChange = () => {
  dataList.value.forEach(item=>{
    setTimeout(()=>{
      item.checked = allSelect.value
    }, 16)
  })
}
/**
 * 提交表单
 */
const submit = async () => {
  loading.value = true

  try {
    await metadata.tableImpsave({
      data: dataList.value.filter(item=>item.checked).map(item=>{
        return [{name: item.name}]
      })
    })

    Message.success('操作成功')
    emit('submit')
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

/**
 * 取消表单
 */
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const getDetailData = () => {}

/**
 * 初始化对话框
 */
const initDialog = id => {
  // 显示对话框
  visible.value = true

  getData()
}

defineExpose({
  initDialog
})

onMounted(()=>{
  getData()
})
</script>

<style scoped lang="scss">
.ivu-list{
  height: 500px;
  overflow-y: auto;
}
</style>